<!--
 * @Author: 胡彪 675473760@qq.com
 * @Date: 2025-08-15 21:15:00
 * @LastEditors: 胡彪 675473760@qq.com
 * @LastEditTime: 2025-08-16 00:48:49
 * @FilePath: \web-cloudbase-vue-template\src\components\SaveLoadModal.vue
 * @Description: 存档/读档弹窗组件
-->
<template>
  <div>
    <!-- Toast 提示组件 - 移到body层级 -->
    <teleport to="body">
      <div v-if="toast.show" class="toast" :class="toast.type">
        {{ toast.message }}
      </div>
    </teleport>
    
    <div v-if="showModal" class="modal-overlay" @click.self="closeModal">
      <div class="modal-content">
        <div class="modal-header">
          <h3>游戏存档</h3>
          <button @click="closeModal" class="close-button">&times;</button>
        </div>
        
        <div class="modal-body">
          <div class="save-section">
            <h4>保存游戏</h4>
            <div class="save-form">
              <input 
                type="text" 
                v-model="saveName" 
                placeholder="存档名称" 
                class="save-input"
              />
              <button @click="saveGame(false)" class="save-button">保存</button>
            </div>
          </div>
          
          <div class="load-section">
            <h4>加载游戏</h4>
            <div v-if="loadingSaves" class="loading-saves">
              加载存档中...
            </div>
            <div v-else-if="saveError" class="save-error">
              {{ saveError }}
            </div>
            <div v-else-if="gameSaves.length === 0" class="no-saves">
              暂无存档
            </div>
            <div v-else class="saves-list">
              <div v-for="(save, index) in gameSaves" :key="index" class="save-item">
                <div class="save-info">
                  <div class="save-name">{{ save.gameName || '未命名存档' }}</div>
                  <div class="save-date">{{ formatDate(save.updateTime) }}</div>
                </div>
                <div class="save-actions">
                  <button @click="loadGame(save._id)" class="load-button">加载</button>
                  <button @click="deleteSave(save._id)" class="delete-button">删除</button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import saveGameService from '../services/saveGameService';
import { ref } from 'vue';

export default {
  name: 'SaveLoadModal',
  props: {
    showModal: {
      type: Boolean,
      required: true
    },
    gameState: {
      type: Object,
      required: true
    },
    isLoggedIn: {
      type: Boolean,
      required: true
    },
    onShowEventMessage: {
      type: Function,
      required: true
    },
    onAutoLogin: {
      type: Function,
      required: true
    },
    onLoadGame: {
      type: Function,
      required: true
    }
  },
  data() {
    return {
      saveName: '',
      gameSaves: [],
      loadingSaves: false,
      saveError: null,
      toast: {
        show: false,
        message: '',
        type: 'success',
        timeout: null
      }
    };
  },
  watch: {
    showModal: {
      immediate: true,
      handler(newVal) {
        if (newVal) {
          console.log('SaveLoadModal - showModal 变为 true，加载存档列表');
          this.loadSavesList();
        }
      }
    }
  },
  
  mounted() {
    console.log('SaveLoadModal - 组件挂载，showModal:', this.showModal);
    if (this.showModal) {
      console.log('SaveLoadModal - 组件挂载时 showModal 为 true，加载存档列表');
      this.loadSavesList();
    }
  },
  methods: {
    closeModal() {
      this.$emit('update:showModal', false);
    },
    
    // Toast 提示方法
    showToast(message, type = 'success') {
      // 清除之前的定时器
      if (this.toast.timeout) {
        clearTimeout(this.toast.timeout);
      }
      
      // 设置新的 toast 内容
      this.toast.show = true;
      this.toast.message = message;
      this.toast.type = type;
      
      // 3秒后自动隐藏
      this.toast.timeout = setTimeout(() => {
        this.toast.show = false;
      }, 3000);
    },
    
    // 存档相关方法
    async loadSavesList() {
      console.log('开始加载存档列表');
      this.loadingSaves = true;
      this.saveError = null;

      try {
        // 确保用户已登录
        if (!this.isLoggedIn) {
          console.log('用户未登录，尝试自动登录');
          await this.onAutoLogin();
          console.log('自动登录完成');
        }
        
        // 获取当前用户ID，用于调试
        const userId = localStorage.getItem('monopoly_user_id');
        console.log('加载存档列表前检查本地存储的用户ID:', userId);
        
        if (!userId) {
          console.warn('本地存储中没有用户ID，尝试重新获取');
          // 尝试从cloudbase获取用户ID
          const cloudbaseUserId = await saveGameService._getUserId();
          console.log('从cloudbase获取的用户ID:', cloudbaseUserId);
        }
        
        // 强制延迟一秒，确保登录状态已更新
        await new Promise(resolve => setTimeout(resolve, 1000));
        
        // 直接检查数据库中是否有存档
        try {
          console.log('直接调用云函数检查存档');
          const cloudbase = await import('../utils/cloudbase').then(m => m.default);
          const result = await cloudbase.callFunction({
            name: 'gameSave',
            data: { 
              action: 'list', 
              data: { userId: localStorage.getItem('monopoly_user_id') } 
            }
          });
          console.log('直接调用云函数结果:', result);
        } catch (e) {
          console.error('直接调用云函数失败:', e);
        }
        
        console.log('调用 saveGameService.getSaves 方法');
        this.gameSaves = await saveGameService.getSaves();
        console.log('获取存档列表成功，数量:', this.gameSaves.length);
        
        if (this.gameSaves.length > 0) {
          console.log('第一个存档信息:', {
            id: this.gameSaves[0]._id,
            name: this.gameSaves[0].gameName,
            userId: this.gameSaves[0].userId
          });
        } else {
          console.log('存档列表为空，尝试重新获取');
          // 再次尝试获取存档列表
          await new Promise(resolve => setTimeout(resolve, 2000)); // 增加等待时间
          this.gameSaves = await saveGameService.getSaves();
          console.log('第二次获取存档列表结果，数量:', this.gameSaves.length);
          
          if (this.gameSaves.length === 0) {
            // 检查是否有保存成功的记录
            console.log('存档列表仍为空，检查是否有保存成功的记录');
            this.saveError = '未找到存档记录，请先保存游戏';
          }
        }
      } catch (error) {
        console.error('加载存档列表失败:', error);
        this.saveError = '加载存档列表失败: ' + (error.message || '未知错误');
      } finally {
        this.loadingSaves = false;
        console.log('存档列表加载完成');
      }
    },
    
    async saveGame(autoSave = false, saveId = null) {
      console.log('开始保存游戏，登录状态:', this.isLoggedIn, '是否自动存档:', autoSave);
      
      try {
        // 确保用户已登录
        if (!this.isLoggedIn) {
          this.saveError = '请先登录';
          console.log('未登录，无法保存游戏');
          
          // 尝试自动登录
          console.log('尝试自动登录');
          await this.onAutoLogin();
          console.log('自动登录成功，继续保存游戏');
          
          // 获取登录后的用户ID，用于调试
          const loginUserId = localStorage.getItem('monopoly_user_id');
          console.log('登录后获取的用户ID:', loginUserId);
        }

        // 修复存档名称逻辑
        let saveName;
        console.log('是否自动存档:', autoSave, this.saveName)
        if (autoSave) {
          saveName = '自动存档';
        } else {
          // 确保使用用户输入的存档名称，如果为空则使用默认名称
          saveName = this.saveName.trim() || '我的存档';
          console.log('用户输入的存档名称:', this.saveName);
        }
        console.log('准备保存游戏，存档名称:', saveName);
        
        // 强制设置一个明确的存档名称，用于测试
        if (!autoSave && this.saveName.trim()) {
          console.log('强制使用用户输入的存档名称:', this.saveName.trim());
          saveName = this.saveName.trim();
        }

        // 准备游戏状态数据
        const gameState = {
          players: this.gameState.players,
          boardCells: this.gameState.boardCells,
          currentPlayerIndex: this.gameState.currentPlayerIndex,
          currentRound: this.gameState.currentRound,
          maxRounds: this.gameState.maxRounds,
          gameEnded: this.gameState.gameEnded,
          playerSpecialStatus: this.gameState.playerSpecialStatus,
          saveDate: new Date()
        };

        // 获取当前用户ID，用于调试
        const userId = localStorage.getItem('monopoly_user_id');
        console.log('保存前检查本地存储的用户ID:', userId);

        // 使用saveGameService保存游戏，确保名称正确传递
        console.log('使用saveGameService保存游戏，传递的存档名称:', saveName);
        const saveResult = await saveGameService.saveGame(gameState, saveId, saveName);
        
        console.log('saveGameService返回结果:', saveResult);
        
        // 获取cloudbase实例，用于后续操作
        const cloudbase = await import('../utils/cloudbase').then(m => m.default);
        
        // 处理返回结果
        let resultData = {};
        if (saveResult && saveResult.data) {
          resultData = saveResult.data;
        } else if (saveResult) {
          resultData = saveResult;
        }
        
        // 获取存档ID和名称
        const newSaveId = resultData.saveId || (resultData.data && resultData.data.saveId) || saveId;
        const savedName = resultData.gameName || (resultData.data && resultData.data.gameName) || saveName;
        console.log('获取到的存档ID:', newSaveId, '存档名称:', savedName);

        // 清空输入框
        if (!autoSave) {
          this.saveName = '';
        }

        // 强制延迟三秒，确保数据库操作完成
        console.log('等待数据库操作完成...');
        await new Promise(resolve => setTimeout(resolve, 3000));

        if (!autoSave && newSaveId) {
          // 强制刷新存档列表
          console.log('强制刷新存档列表');
          this.gameSaves = []; // 先清空列表
          this.loadingSaves = true; // 显示加载中
          
          try {
            // 直接调用云函数获取最新存档列表
            const result = await cloudbase.callFunction({
              name: 'gameSave',
              data: { action: 'list', data: { userId } }
            });
            
            console.log('直接从云函数获取的存档列表:', result);
            
            if (Array.isArray(result)) {
              this.gameSaves = result;
            } else if (result && Array.isArray(result.data)) {
              this.gameSaves = result.data;
            }
          } catch (listError) {
            console.error('直接获取存档列表失败:', listError);
          } finally {
            // 如果直接调用失败，再尝试通过服务获取
            if (this.gameSaves.length === 0) {
              try {
                this.gameSaves = await saveGameService.getSaves();
              } catch (serviceError) {
                console.error('通过服务获取存档列表失败:', serviceError);
              }
            }
            
            this.loadingSaves = false;
          }
          
          console.log('存档列表刷新完成，数量:', this.gameSaves.length);
          
          // 显示 Toast 提示
          this.showToast(`游戏已成功保存为"${savedName}"`, 'success');
          
          // 显示成功消息
          this.onShowEventMessage(
            '保存成功',
            `游戏已成功保存为"${savedName}"`,
            [{ text: '确定', action: 'confirm' }]
          );
        }
      } catch (error) {
        console.error('保存游戏失败:', error);
        if (!autoSave) {
          this.saveError = '保存游戏失败: ' + (error.message || '未知错误');
          this.onShowEventMessage(
            '保存失败',
            '保存游戏失败，请稍后再试: ' + (error.message || '未知错误'),
            [{ text: '确定', action: 'confirm' }]
          );
        }
      }
    },
    
    async loadGame(saveId) {
      try {
        const gameState = await saveGameService.loadGame(saveId);
        
        // 通知父组件加载游戏
        this.onLoadGame(gameState);
        
        // 关闭存档菜单
        this.closeModal();
      } catch (error) {
        console.error('加载游戏失败:', error);
        this.onShowEventMessage(
          '加载失败', 
          '加载游戏存档失败，请稍后再试', 
          [{ text: '确定', action: 'confirm' }]
        );
      }
    },
    
    async deleteSave(saveId) {
      try {
        await saveGameService.deleteSave(saveId);
        // 显示 Toast 提示
        this.showToast('存档已成功删除', 'success');
        // 刷新存档列表
        this.loadSavesList();
      } catch (error) {
        console.error('删除存档失败:', error);
        this.saveError = '删除存档失败';
        // 显示错误 Toast
        this.showToast('删除存档失败', 'error');
      }
    },
    
    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return '未知时间';
      
      const date = new Date(dateStr);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
    }
  }
};
</script>

<style scoped>
/* Toast 提示样式 */
.toast {
  position: fixed;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  padding: 12px 20px;
  border-radius: 4px;
  color: white;
  font-weight: bold;
  z-index: 99999; /* 进一步提高z-index确保显示在最上层 */
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.5);
  animation: toastIn 0.3s ease-out;
  pointer-events: none; /* 确保Toast不会阻挡点击事件 */
  width: auto;
  max-width: 80%;
  height: auto; /* 确保高度由内容撑开 */
  min-height: fit-content; /* 使用fit-content确保高度适应内容 */
  display: inline-block; /* 使元素宽度由内容决定 */
  white-space: nowrap; /* 防止文本换行 */
}

.toast.success {
  background-color: #4CAF50;
}

.toast.error {
  background-color: #F44336;
}

.toast.info {
  background-color: #2196F3;
}

@keyframes toastIn {
  from { transform: translate(-50%, -20px); opacity: 0; }
  to { transform: translate(-50%, 0); opacity: 1; }
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  border-radius: 10px;
  width: 90%;
  max-width: 500px;
  max-height: 80vh;
  overflow-y: auto;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
  animation: modalAppear 0.3s ease-out;
}

@keyframes modalAppear {
  from { transform: translateY(-30px); opacity: 0; }
  to { transform: translateY(0); opacity: 1; }
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
}

.modal-header h3 {
  margin: 0;
  color: #333;
  font-size: 20px;
}

.close-button {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
  transition: color 0.2s;
}

.close-button:hover {
  color: #333;
}

.modal-body {
  padding: 20px;
}

/* 存档/读档弹窗样式 */
.save-section, .load-section {
  margin-bottom: 20px;
}

.save-section h4, .load-section h4 {
  margin-top: 0;
  margin-bottom: 15px;
  color: #4CAF50;
  border-bottom: 1px solid #eee;
  padding-bottom: 8px;
}

.save-form {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.save-input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.save-button {
  background-color: #4CAF50;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-weight: bold;
  transition: all 0.2s;
}

.save-button:hover {
  background-color: #388E3C;
}

.loading-saves, .save-error, .no-saves {
  padding: 15px;
  text-align: center;
  background-color: #f9f9f9;
  border-radius: 4px;
  margin-bottom: 10px;
}

.loading-saves {
  color: #2196F3;
}

.save-error {
  color: #F44336;
}

.no-saves {
  color: #9E9E9E;
}

.saves-list {
  max-height: 300px;
  overflow-y: auto;
}

.save-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  border-bottom: 1px solid #eee;
  transition: background-color 0.2s;
}

.save-item:hover {
  background-color: #f5f5f5;
}

.save-info {
  flex: 1;
}

.save-name {
  font-weight: bold;
  margin-bottom: 4px;
}

.save-date {
  font-size: 12px;
  color: #777;
}

.save-actions {
  display: flex;
  gap: 8px;
}

.load-button, .delete-button {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  transition: all 0.2s;
}

.load-button {
  background-color: #2196F3;
  color: white;
}

.load-button:hover {
  background-color: #1976D2;
}

.delete-button {
  background-color: #F44336;
  color: white;
}

.delete-button:hover {
  background-color: #D32F2F;
}
</style>